const crypto = require('crypto');

module.exports = {
    passwordEncoder: function(raw_password) {
        return crypto
            .createHmac('sha256', 'aaa')
            .update(raw_password)
            .digest('hex');
    },
    dateFormat(date) {
        if (date instanceof Date) {
            return this.toLocalDateString(date);
        }

        // 先转成 date 对象，在调用封装的格式化函数
        date = new Date(Date.parse(date));
        return this.toLocalDateString(date);
    },
    toLocalDateString(date) {
        const Y = date.getFullYear();
        const M = String(date.getMonth() + 1).padStart(2, '0');
        const D = String(date.getDate()).padStart(2, '0');

        const hh = String(date.getHours()).padStart(2, '0');
        const mm = String(date.getMinutes()).padStart(2, '0');
        const ss = String(date.getSeconds()).padStart(2, '0');
        // 2020-06-15 11:23:10
        return `${Y}-${M}-${D} ${hh}:${mm}:${ss}`;
    },
    randomArr(arr) {
        return arr.sort(() => (Math.random() < 0.5 ? -1 : 1));
    },
    isPalindrome(str) {
        return (
            str
                .split('')
                .reverse()
                .join('') === str
        );
    },
    formatPhoneNumber(str) {
        // 如果是手机号
        if (/^1(3|4|5|7|8)\d{9}$/.test(str)) {
            return `${str.substring(0, 3)} ${str.substring(
                3,
                7,
            )} ${str.substring(7, 11)}`;
        }
    },
};
